package main

import (
	"fmt"
	"strings"
	//"github.com/ngaut/log"
)

// 空的slice与nil的区别：
// https://stackoverflow.com/questions/44305170/nil-slices-vs-non-nil-slices-vs-empty-slices-in-go-language


type someStruct2 struct {
	x int
}


func tSlice() {
	var ar [10]int = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	var slice []int = ar[:5] //基于数组创建分片,左闭右开
	slice = ar[1:5]
	slice = ar[:] // 将数组完全赋给slice
	slice = ar[:5]
	
	fmt.Println("array:")
	for i, v := range ar {
		if ar[i] != v {
			panic(fmt.Errorf("not equal"))
		}
	}

	fmt.Print("\nslice based on array:")
	for _, v := range slice {
		fmt.Print(v, " ")
	}

	s1 := make([]int, 5)     //大小为5，初始值为0
	s2 := make([]int, 5, 10) //大小为5，初始值为0，并预留10
	s3 := []int{1, 2, 3, 4, 5}
	s1 = append(s1, s3...) //将s3元素打散后，赋给s1
	fmt.Printf("\nlen(s1):%d, cap(s1)=%d\n", len(s1), cap(s1))
	fmt.Printf("len(s2):%d, cap(s2)=%d\n", len(s2), cap(s2))
	fmt.Printf("len(s3):%d, cap(s3)=%d\n", len(s3), cap(s3))

	//copy
	copy(s2, s1) // 由于s2大小小，所以只有s1的前5个元素被拷贝
	fmt.Println("\ncopyed slice by `call`:")
	for _, v := range s2 {
		fmt.Print(v, " ")
	}
	fmt.Println()

	fmt.Println("testing slice created from string: ")
	var s string = "-a A -b     B"
	sl := strings.Split(s, " ")
	fmt.Println("Split(spaces kept): ", sl, len(sl))

	sl = strings.Fields(s)
	fmt.Println("Fields(exclude space, tab, CR): ", sl, len(sl))

	// 手工解析命令行
	for i := 0; i < len(sl); i++ {
		fmt.Println("i=", i)
		switch sl[i][1:] {
		case "a":
			i++
			fmt.Println(sl[i])
		case "b":
			i++
			fmt.Println(sl[i])
		default:
			i++
			fmt.Println("error option")
		}
	}

	//https://stackoverflow.com/a/26166046/6328514
	fmt.Println("building slice of annoymous struct ...")
	var opts = []struct {
		shortnm      byte
		longnm, help string
		needArg      bool
	}{
		{'a', "multiple", "Usage for a", false},
		{
			shortnm: 'b',
			longnm:  "b-option",
			needArg: false,
			help:    "Usage for b",
		},
	}
	fmt.Println(opts)

	fmt.Println("testing slice of named struct ...")
	sfoo := someStruct2{1}
	fooslice := []someStruct2{sfoo}
	fmt.Println(fooslice)

	foo2slice := []someStruct2{
		{1},
		{2},
	}
	fmt.Println(foo2slice)

}

